#include <QFont>
#include <controls/table/cxitablemodel.h>
#include <common/logger/logger.h>

CxiTableModel::CxiTableModel(QObject* parent)
	: QAbstractTableModel(parent)
{
}

void CxiTableModel::setColumnConfig(const QList<cxitable::GridColumnConfig>& configs)
{
	d_columns = configs;
}

CxiTableModel::~CxiTableModel()
{
}

bool CxiTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
	if (!index.isValid() || index.row() > rowCount() || index.column() > columnCount())
	{
		LOG_WARN("模型数据异常！");
		return false;
	}
	auto column = d_columns.at(index.column());
	return setFieldData(index, role, column.field, value);
}

QVariant CxiTableModel::data(const QModelIndex& index, int role) const
{
	if (!index.isValid() || index.row() > rowCount() || index.column() > columnCount())
	{
		LOG_WARN("模型数据异常！");
		return {};
	}
	auto column = d_columns.at(index.column());

	switch (role)
	{
	case Qt::DisplayRole:
	case Qt::EditRole:
		return fieldData(index, role, column.field);

	case Qt::TextAlignmentRole:
		// 列对齐方式
		return static_cast<int>(column.textAlignment);

	case Qt::FontRole:
		return column.isBold ? QFont(QFont().defaultFamily(), -1, QFont::Bold) : QVariant();

	default:
		break;
	}
	return {};
}

int CxiTableModel::columnCount(const QModelIndex& parent) const
{
	return d_columns.size();
}

Qt::ItemFlags CxiTableModel::flags(const QModelIndex& index) const
{
	if (!index.isValid()) return Qt::NoItemFlags;

	const cxitable::GridColumnConfig& col = d_columns.at(index.column());
	Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
	if (!col.readOnly) f |= Qt::ItemIsEditable;
	return f;
}